/**
 * 鼠标点击动画类
 */
class ClickMC extends egret.DisplayObjectContainer {
  name: string; // 动画名称
  mcObj: egret.MovieClip;
  static mcFactoryDict: {[key: string]: egret.MovieClipDataFactory} = {};
  constructor(name: string) {
    super();
    this.name = name;
  }

  /**
   * 显示特效方法
   * @param name 动画名称
   * @param x 显示位置横坐标
   * @param y 显示位置纵坐标
   */
  static show(name: string, x: number, y: number): void {
    let clickMCObj = ObjectPool.getObj(name) as ClickMC; // 从对象池获取
    if (!clickMCObj) {
      console.log('创建ClickMC对象');
      clickMCObj = new ClickMC(name);
    }
    clickMCObj.x = x;
    clickMCObj.y = y;
    clickMCObj.showClickMC();
  }

  /**
   * 播放MC动画
   */
   private async showClickMC() {
    // 异步加载（缓存有则直接回调返回，否则启动网络加载并解析后回调）
    const jsonResource: JSON = await RES.getResAsync(this.name + '_mc_json')
    const pngResource: egret.Texture = await RES.getResAsync(this.name + '_tex_png')

    let mcFactory: egret.MovieClipDataFactory = ClickMC.mcFactoryDict[this.name];
    if (!mcFactory) {
      console.log('创建MovieClip工厂类实例');
      mcFactory = new egret.MovieClipDataFactory(jsonResource, pngResource); // 创建MovieClip工厂类实例
      ClickMC.mcFactoryDict[this.name] = mcFactory;
    }
    if (!this.mcObj) {
      console.log('创建MovieClip对象');
      this.mcObj = new egret.MovieClip(mcFactory.generateMovieClipData(this.name));
    }
    this.mcObj.addEventListener(egret.Event.COMPLETE, this.onMovieClipComplete, this); // 增加播放完毕的事件监听
    this.addChild(this.mcObj);
    this.mcObj.gotoAndPlay(1, 1); // 从第1帧开始播放1次
    const mainStage = egret.MainContext.instance.stage;
    mainStage.addChild(this);
  }

  /**
   * 点击动画播放完毕后执行
   */
  private onMovieClipComplete(): void {
    this.mcObj.removeEventListener(egret.Event.COMPLETE, this.onMovieClipComplete, this);
    this.parent.removeChild(this);
    ObjectPool.cache(this.name, this); // 存进对象池
  }
}